﻿@using Gurux.DLMS.AMI.Shared.DIs

@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.DTOs.Authentication
@using Gurux.DLMS.AMI.Shared.Rest
@using Microsoft.AspNetCore.SignalR.Client
@using Gurux.DLMS.AMI.Shared
@using Gurux.DLMS.AMI.Shared.Enums
@using Gurux.DLMS.AMI.Client.Helpers
@using Gurux.DLMS.AMI.Module
@using System.Linq

@if (Scripts != null)
{
    @if (!string.IsNullOrEmpty(Title))
    {
        <label style="margin:auto">@Title</label>
    }
    <div class="d-inline-flex">
        <select class="form-select" @bind="@ScriptMethod">
            <!--Empty option is used to reset selection.-->
            <option></option>
            @foreach (var script in Scripts)
            {
                @if (script.Methods != null)
                {
                    @foreach (var method in script.Methods)
                    {
                        <option value="@method.Id">@(script.Name + "." + method.Name)</option>
                    }
                }
            }
        </select>
        <AuthorizeView Roles=@GXRoles.ToString(GXRoles.Admin, GXRoles.Script, GXRoles.ScriptGroupManager)>
            &nbsp;<a target="_blank" href="@GetScriptId()">@Properties.Resources.Manage</a>
        </AuthorizeView>
    </div>
}

@code {
    Guid? _scriptMethod;

    [Parameter]
    public GXScript[]? Scripts { get; set; }

    [Parameter]
    public string? Title { get; set; }


    [Parameter]
    public Guid? ScriptMethod
    {
        get
        {
            return _scriptMethod;
        }
        set
        {
            bool changed = _scriptMethod != value;
            _scriptMethod = value;
            if (changed)
            {
                SelectionChanged?.Invoke(value);
            }
        }
    }

    private string GetScriptId()
    {
        if (Scripts != null)
        {
            foreach (var script in Scripts)
            {
                if (script.Methods != null)
                {
                    @foreach (var method in script.Methods)
                    {
                        if (method.Id == _scriptMethod)
                        {
                            return "Config/Script/Edit/" + script.Id;
                        }
                    }
                }
            }
        }
        return "Config/Script";
    }

    /// <summary>
    /// User has selected a new script.
    /// </summary>
    [Parameter]
    public Action<Guid?>? SelectionChanged { get; set; }
}
